/*
 * @lc app=leetcode.cn id=202 lang=javascript
 *
 * [202] 快乐数
 */

// @lc code=start
/**
 * @param {number} n
 * @return {boolean}
 */
var isHappy = function (n) {
  const set = new Set();

  let next = getNext(n);

  while (next !== 1 && !set.has(next)) {
    set.add(next);

    next = getNext(next);
  }

  return next === 1;
};

var getNext = function (n) {
  let nums = String(n).split('');

  return nums.reduce((pre, cur) => {
    return pre + Math.pow(cur, 2);
  }, 0);
};
// @lc code=end

// @after-stub-for-debug-begin
module.exports = isHappy;
// @after-stub-for-debug-end
